import multer from 'multer'
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'
import { existsSync, mkdirSync } from 'fs'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

// 确保上传目录存在
const uploadDir = join(__dirname, '../uploads')
if (!existsSync(uploadDir)) {
  mkdirSync(uploadDir, { recursive: true })
}

// 配置存储
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadDir)
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1E9)}`
    const ext = file.originalname.split('.').pop()
    cb(null, `${file.fieldname}-${uniqueSuffix}.${ext}`)
  }
})

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 允许的图片格式
  const allowedMimes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp']
  if (allowedMimes.includes(file.mimetype)) {
    cb(null, true)
  } else {
    cb(new Error('只支持 JPG、PNG、WEBP 格式的图片'), false)
  }
}

// 创建上传中间件
export const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB
  }
})

// 将文件路径转换为URL
export function getFileUrl(filename) {
  return `/uploads/${filename}`
}






